<?php

namespace App\Http\Controllers;

use App\Models\Brand;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ProductTranslation;
use App\Models\ProductStock;
use App\Models\Category;
use App\Models\FlashDealProduct;
use App\Models\ProductTax;
use App\Models\AttributeValue;
use App\Models\Attribute;
use App\Models\Cart;

use App\Models\Role;
use App\Models\Staff;
use App\Models\FlashDeal;
use App\Models\User;
use App\Models\Color;
use App\Models\Seller;
use Auth;
use App\Models\Upload;
use Carbon\Carbon;
use Combinations;
use Artisan;
use Cache;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Str;
use App\Models\Shop;
use App\Models\BusinessSetting;
use App\Jobs\ScrapeAndStoreProduct;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\RetryMiddleware;


class ProductController extends Controller
{


    public function addbu(Request $request)
    {
        $id = $request->id;
        $val = $request->val;
        $att = new AttributeValue;
        $att->attribute_id = $id;
        $att->value = $val;
        $att->save();
        echo $att->id;
    }

    public function addabb(Request $request)
    {

        $val = $request->val;
        $att = new Attribute;

        $att->name = $val;
        $att->save();
        echo $att->id;
    }

    public function addcolor(Request $request)
    {
        $name = $request->name;
        $code = $request->color;
        $color = new Color;
        $color->name = $name;
        $color->code = $code;
        $color->save();
        echo '1';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function admin_products(Request $request)
    {

        $type = 'In House';
        $col_name = null;
        $query = null;
        $sort_search = null;

        $products = Product::where('added_by', 'admin')->where('auction_product', 0)->where('wholesale_product', 0);

        if ($request->type != null) {
            $var = explode(",", $request->type);
            $col_name = $var[0];
            $query = $var[1];
            $products = $products->orderBy($col_name, $query);
            $sort_type = $request->type;
        }
        if ($request->search != null) {
            $sort_search = $request->search;
            $products = $products
                ->where('name', 'like', '%' . $sort_search . '%')
                ->orWhereHas('stocks', function ($q) use ($sort_search) {
                    $q->where('sku', 'like', '%' . $sort_search . '%');
                });

        }

        $products = $products->where('digital', 0)->orderBy('created_at', 'desc')->paginate(15);
        $cpk = 0;

        $show_index = @file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/showindex.txt');
        $show_index = intval($show_index);


        return view('backend.product.products.index', compact('products', 'type', 'col_name', 'query', 'sort_search', 'cpk', 'show_index'));
    }

    public function admin_products2(Request $request)
    {
        $type = 'In House';
        $col_name = null;
        $query = null;
        $sort_search = null;

        $products = Product::where('added_by', 'admin')->where('auction_product', 0)->where('wholesale_product', 0)->where('cpk', 1);

        if ($request->type != null) {
            $var = explode(",", $request->type);
            $col_name = $var[0];
            $query = $var[1];
            $products = $products->orderBy($col_name, $query);
            $sort_type = $request->type;
        }
        if ($request->search != null) {
            $sort_search = $request->search;
            $products = $products
                ->where('name', 'like', '%' . $sort_search . '%')
                ->orWhereHas('stocks', function ($q) use ($sort_search) {
                    $q->where('sku', 'like', '%' . $sort_search . '%');
                });

        }

        $products = $products->where('digital', 0)->orderBy('created_at', 'desc')->paginate(15);
        $cpk = 1;
        return view('backend.product.products.index', compact('products', 'type', 'col_name', 'query', 'sort_search', 'cpk'));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function seller_products(Request $request)
    {
        $col_name = null;
        $query = null;
        $seller_id = null;
        $sort_search = null;
        $products = Product::where('added_by', 'seller')->where('auction_product', 0)->where('wholesale_product', 0)->where('cpk', 0);
        if ($request->has('user_id') && $request->user_id != null) {
            $products = $products->where('user_id', $request->user_id);
            $seller_id = $request->user_id;
        }
        if ($request->search != null) {
            $products = $products
                ->where('name', 'like', '%' . $request->search . '%');
            $sort_search = $request->search;
        }
        if ($request->type != null) {
            $var = explode(",", $request->type);
            $col_name = $var[0];
            $query = $var[1];
            $products = $products->orderBy($col_name, $query);
            $sort_type = $request->type;
        }

        $products = $products->where('digital', 0)->orderBy('created_at', 'desc')->paginate(15);
        $type = 'Seller';
        $cpk = 1;
        return view('backend.product.products.index', compact('products', 'type', 'col_name', 'query', 'seller_id', 'sort_search', 'cpk'));
    }

    public function all_products(Request $request)
    {
        $col_name = null;
        $query = null;
        $seller_id = null;
        $sort_search = null;
        $products = Product::orderBy('created_at', 'desc')->where('auction_product', 0)->where('wholesale_product', 0);
        if ($request->has('user_id') && $request->user_id != null) {
            $products = $products->where('user_id', $request->user_id);
            $seller_id = $request->user_id;
        }
        if ($request->search != null) {
            $sort_search = $request->search;
            $products = $products
                ->where('name', 'like', '%' . $sort_search . '%')
                ->orWhereHas('stocks', function ($q) use ($sort_search) {
                    $q->where('sku', 'like', '%' . $sort_search . '%');
                });

        }
        if ($request->type != null) {
            $var = explode(",", $request->type);
            $col_name = $var[0];
            $query = $var[1];
            $products = $products->orderBy($col_name, $query);
            $sort_type = $request->type;
        }

        $products = $products->paginate(15);
        $type = 'All';
        $cpk = '2';


        return view('backend.product.products.index', compact('products', 'type', 'col_name', 'query', 'seller_id', 'sort_search', 'cpk'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

    private function cget($url)
    {

        $uid = 0;
        $shop = new Shop;
        #$shop_info = $shop->where(['user_id'=>$uid])->first();
        $shop_info = BusinessSetting::where('type', 'dl_link')->first();


        $dl_link = get_setting('dl_link');
        #$dl_link = 'https://proxy.qg.net/extract?Key=C2580493&Num=1&AreaId=&Isp=&DataFormat=txt&DataSeparator=%5Cr%5Cn&Detail=0';
        if ($dl_link) {
            $dlip = file_get_contents($dl_link);
            #$dlip = '182.54.99.109:27480';

            list($ip, $port) = explode(':', $dlip);
        }

        #$u = 'http://getip.beikeruanjian.com/getip/?user_id=20210425121021874461&token=azL51KZIN26sqMOH&server_id=16312&num=1&protocol=1&format=txt&ss=1&dr=0&province=1&city=1&citycode=';

        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);


        if ($ip && $port) {
            curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
            curl_setopt($curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
            curl_setopt($curl, CURLOPT_PROXY, $ip);
            curl_setopt($curl, CURLOPT_PROXYPORT, $port);
        }

        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0');
        #curl_setopt ( $curl, CURLOPT_COOKIE, 'session-id=457-3894493-1379032; i18n-prefs=CNY; ubid-acbcn=462-3890271-9038902; arp_scroll_position=100; session-token=UfsvkcOfaW0tPKyUxd/znPifg4hVKBe3YNZS/toRfOfVORX2WeztWk/2w7I8QQ6LOVYu4/U+tSdf8HdSbgXJAFLR/7ewCAn4AIvFH64bjxrn/HbqSTLAE1EGgxHL0GqHcV+IIkE0QNh//k79KmjLegUXM4YkWT8BGW87ro1uL2Wf4Js5eC8NNozGDFGRS7kd; csm-hit=tb:s-BXPMWMR6SSWKCFKPMJRJ|1646982700894&t:1646982701742&adb:adblk_no; session-id-time=2082729601l');


        //执行命令
        $data = curl_exec($curl);
        file_put_contents(dirname(__FILE__) . '/html.txt', $data);
        //关闭URL请求
        curl_close($curl);

        return $data;
    }

    public function create2(Request $request)
    {
        error_reporting(0);
        $url = $request->url;

        if (empty($url)) {
            echo json_encode(['code' => 0, 'msg' => '请填入亚马逊地址']);
            exit;
        }
        if (strpos($url, 'amazon') === false) {
            echo json_encode(['code' => 0, 'msg' => '填入的地址不对']);
            exit;
        }
        # file_put_contents(dirname(__FILE__).'/1.txt');
        #$html = file_get_contents(dirname(__FILE__).'/1.txt');
        $html = $this->cget($url);

        @ file_put_contents(dirname(__FILE__) . '/1.txt', $html);

        preg_match('#<span id="productTitle" class="(?:.*)">(.*)</span>#iUs', $html, $title);
        preg_match('#<div id="detailBullets_feature_div">(.*)</div>#iUs', $html, $desc);
        preg_match_all('#"large":"(.*)"#iUs', $html, $imgs);

        $title = trim($title['1']);
        $detail = trim($desc['1']);


        if (empty($detail)) {
            preg_match('#id="productDescription" class="(?:.*)">(.*)</div>#iUs', $html, $desc);
            $detail = trim($desc['1']);


            # preg_match('#<div id="(.*)" class="(?:.*)">(.*)</div>#iUs',$html, $desc );
        }
        if (empty($detail)) {
            preg_match('#id="prodDetails" class="(?:.*)">(.*)</div>#iUs', $html, $desc);
            $detail = trim($desc['1']);


            # preg_match('#<div id="(.*)" class="(?:.*)">(.*)</div>#iUs',$html, $desc );
        }
        if (empty($detail)) {
            preg_match('#id="productDescription_feature_div" class="(?:.*)">(.*)</div>#iUs', $html, $desc);
            $detail = trim($desc['1']);
            echo $detail;
            exit;
        }

        $detail = str_replace('src="//u.alicdn.com/js/5v/esite/img/img-placeholder.png"', '', $detail);
        $detail = str_replace('data-src', 'src', $detail);


        $mm = $imgs[1];
        $mm = array_unique($mm);

        $data['title'] = $title;
        $data['imgs'] = $mm;
        $data['content'] = $detail;


        echo json_encode(['code' => 1, 'msg' => 'ok', 'data' => $data]);
        exit;


        print_r($title);
        exit;


        preg_match('#window\.detailData\s+=\s+(.*)</script>#iUs', $html, $json);


        $json = $json[1];
        $arr = json_decode($json, true);
        $title = $arr['globalData']['product']['subject'];
        $imgs = $arr['globalData']['product']['mediaItems'];
        $did = $arr['globalData']['product']['productId'];
        $mm = [];
        foreach ($imgs as $k => $img) {
            if (!empty($img['imageUrl']['big'])) {
                $mm[] = $img['imageUrl']['big'];
            }
        }
        $descurl = "https://www.alibaba.com/event/app/mainAction/desc.htm?detailId={$did}&language=en";
        $descjson = $this->cget($descurl);
        $descarr = json_decode($descjson, true);
        $detail = $descarr['data']['productHtmlDescription'];
        $detail = str_replace('src="//u.alicdn.com/js/5v/esite/img/img-placeholder.png"', '', $detail);
        $detail = str_replace('data-src', 'src', $detail);
        $data['title'] = $title;
        $data['imgs'] = $mm;
        $data['content'] = $detail;


        echo json_encode(['code' => 1, 'msg' => 'ok', 'data' => $data]);
        exit;

        $encode = mb_detect_encoding($html, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
        $html = mb_convert_encoding($html, 'UTF-8', $encode);

        echo $html;
        exit;
        #$html = iconv("GBK","UTF-8", $html );

        #@file_put_contents(dirname(__FILE__).'/1688.txt', $html );
        #$html = file_get_contents(dirname(__FILE__).'/1688.txt');
        if (strpos($html, 'uuid') !== false) {
            preg_match('#"uuid":"(.*)"#iUs', $html, $uuid);
            $uuid = $uuid[1];
            preg_match("#window\.__INIT_DATA=(.*)</script>#iUs", $html, $arr);
            $json = $arr['1'];
            $arr = json_decode($json, true);
            #$arr['data'][$uuid]['data']['detail'] = $this->cget($details_url);
            $data['title'] = $arr['data'][$uuid]['data']['subject'];
            $data['imgs'] = $arr['data'][$uuid]['data']['offerImgList'];
            $data['content'] = "";
            echo json_encode(['code' => 1, 'msg' => 'ok', 'data' => $data]);
        } else {

            preg_match('#<h1 class="d-title">(.*)</h1>#iUs', $html, $title);
            $title = $title[1];
            preg_match('#data-tfs-url="(.*)"#iUs', $html, $details);
            $details_url = $details[1];
            $detail = $this->cget($details_url);
            $detail = str_replace('var offer_details=', '', $detail);
            $detail = str_replace('"};', '"}', $detail);
            $detail = json_decode($detail, true);
            $detail = $detail['content'];

            preg_match_all('#class="box-img" href="(?:.*)"\s+hidefocus="true">\s+<img src="(.*)"#iUs', $html, $imgs);
            $imgs = $imgs[1];
            foreach ($imgs as $k => &$v) {
                if (strpos($v, 'lazyload') !== false) {
                    unset($imgs[$k]);
                    continue;
                }
                $v = str_replace('.60x60', '', $v);
            }

            $encode = mb_detect_encoding($title, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
            $title = mb_convert_encoding($title, 'UTF-8', $encode);
            $data['title'] = $title;
            $data['imgs'] = $imgs;
            $data['content'] = $detail;


            echo json_encode(['code' => 1, 'msg' => 'ok', 'data' => $data]);
            exit;

        }


    }


    public function create()
    {

        $categories = Category::where('parent_id', 0)
            ->where('digital', 0)
            ->with('childrenCategories')
            ->get();

        return view('backend.product.products.create', compact('categories'));
    }

    public function add_more_choice_option(Request $request)
    {
        $all_attribute_values = AttributeValue::with('attribute')->where('attribute_id', $request->attribute_id)->get();

        $html = '';

        foreach ($all_attribute_values as $row) {
            $html .= '<option value="' . $row->value . '">' . $row->value . '</option>';
        }

        echo json_encode($html);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request)
    {

        $product = new Product;
        $product->name = $request->name;
        $product->added_by = $request->added_by;
        if (Auth::user()->user_type == 'seller') {
            $product->user_id = Auth::user()->id;
            if (get_setting('product_approve_by_admin') == 1) {
                $product->approved = 0;
            }
        } else {
            $product->user_id = User::where('user_type', 'admin')->first()->id;
        }
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->barcode = $request->barcode;
        # $product->click     = $request->click;
        ### $product->collect     = $request->collect;
        if (addon_is_activated('refund_request')) {
            if ($request->refundable != null) {
                $product->refundable = 1;
            } else {
                $product->refundable = 0;
            }
        }
        $product->photos = $request->photos;
        $product->thumbnail_img = $request->thumbnail_img;
        $product->unit = $request->unit;

        #$product->cb_price = $request->cb_price;
        #$product->xn_salenum = $request->xn_salenum;
        $product->min_qty = $request->min_qty;
        $product->low_stock_quantity = $request->low_stock_quantity;
        $product->stock_visibility_state = $request->stock_visibility_state;
        $product->external_link = $request->external_link;
        $product->external_link_btn = $request->external_link_btn;


        $mid = time() . mt_rand(100, 999);
        if (isset($_POST['thumbs'])) {
            foreach ($_POST['thumbs'] as $img) {

                $upload = new Upload;
                $upload->user_id = Auth::user()->id;
                $upload->file_size = 8888;
                $upload->extension = 'jpg';
                $upload->type = 'image';
                $upload->file_original_name = $upload->file_name = $img;
                $upload->mid = $mid;
                $upload->save();

                #echo $img;

            }
        }

        $thm_id = 0;
        $upload = new Upload;
        $all = $upload->where(['mid' => $mid])->get()->toArray();;

        $ids = '';
        foreach ($all as $a => $v) {
            if ($a == 0) {
                $thm_id = $v['id'];
            }
            $ids .= $v['id'] . ',';
        }
        $ids = rtrim($ids, ',');


        $tags = array();
        if ($request->tags[0] != null) {
            foreach (json_decode($request->tags[0]) as $key => $tag) {
                array_push($tags, $tag->value);
            }
        }
        $product->tags = implode(',', $tags);

        $product->description = $request->description;
        $product->video_provider = $request->video_provider;
        $product->video_link = $request->video_link;
        $product->unit_price = $request->unit_price;
        $product->purchase_price = $request->purchase_price;
        $product->discount = $request->discount;
        $product->discount_type = $request->discount_type;


        if (isset($_POST['thumbs'][0])) {
            $product->thumbnail_img = $thm_id;

        }
        // $product->photos = $ids;

        if ($request->date_range != null) {
            $date_var = explode(" to ", $request->date_range);
            $product->discount_start_date = strtotime($date_var[0]);
            $product->discount_end_date = strtotime($date_var[1]);
        }

        $product->shipping_type = $request->shipping_type;
        $product->est_shipping_days = $request->est_shipping_days;

        if (addon_is_activated('club_point')) {
            if ($request->earn_point) {
                $product->earn_point = $request->earn_point;
            }
        }

        if ($request->has('shipping_type')) {
            if ($request->shipping_type == 'free') {
                $product->shipping_cost = 0;
            } elseif ($request->shipping_type == 'flat_rate') {
                $product->shipping_cost = $request->flat_shipping_cost;
            } elseif ($request->shipping_type == 'product_wise') {
                $product->shipping_cost = json_encode($request->shipping_cost);
            }
        }
        if ($request->has('is_quantity_multiplied')) {
            $product->is_quantity_multiplied = 1;
        }

        $product->meta_title = $request->meta_title;
        $product->meta_description = $request->meta_description;

        if ($request->has('meta_img')) {
            $product->meta_img = $request->meta_img;
        } else {
            $product->meta_img = $product->thumbnail_img;
        }

        if ($product->meta_title == null) {
            $product->meta_title = $product->name;
        }

        if ($product->meta_description == null) {
            $product->meta_description = strip_tags($product->description);
        }

        if ($product->meta_img == null) {
            $product->meta_img = $product->thumbnail_img;
        }

        if ($request->hasFile('pdf')) {
            $product->pdf = $request->pdf->store('uploads/products/pdf');
        }

        $product->slug = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($request->name)));

        if (Product::where('slug', $product->slug)->count() > 0) {
            flash(translate('Another product exists with same slug. Please change the slug!'))->warning();
            return back();
        }

        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $product->colors = json_encode($request->colors);
        } else {
            $colors = array();
            $product->colors = json_encode($colors);
        }

        $choice_options = array();

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $str = 'choice_options_' . $no;

                $item['attribute_id'] = $no;

                $data = array();
                // foreach (json_decode($request[$str][0]) as $key => $eachValue) {
                foreach ($request[$str] as $key => $eachValue) {
                    // array_push($data, $eachValue->value);
                    array_push($data, $eachValue);
                }

                $item['values'] = $data;
                array_push($choice_options, $item);
            }
        }

        if (!empty($request->choice_no)) {
            $product->attributes = json_encode($request->choice_no);
        } else {
            $product->attributes = json_encode(array());
        }

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);

        $product->published = 1;
        if ($request->button == 'unpublish' || $request->button == 'draft') {
            $product->published = 0;
        }

        if ($request->has('cash_on_delivery')) {
            $product->cash_on_delivery = 1;
        }
        if ($request->has('featured')) {
            $product->featured = 1;
        }
        if ($request->has('todays_deal')) {
            $product->todays_deal = 1;
        }
        $product->cash_on_delivery = 0;
        if ($request->cash_on_delivery) {
            $product->cash_on_delivery = 1;
        }
        //$variations = array();

        $product->save();

        //VAT & Tax
        if ($request->tax_id) {
            foreach ($request->tax_id as $key => $val) {
                $product_tax = new ProductTax;
                $product_tax->tax_id = $val;
                $product_tax->product_id = $product->id;
                $product_tax->tax = $request->tax[$key];
                $product_tax->tax_type = $request->tax_type[$key];
                $product_tax->save();
            }
        }
        //Flash Deal
        if ($request->flash_deal_id) {
            $flash_deal_product = new FlashDealProduct;
            $flash_deal_product->flash_deal_id = $request->flash_deal_id;
            $flash_deal_product->product_id = $product->id;
            $flash_deal_product->save();
        }

        //combinations start
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        }

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                foreach ($request[$name] as $key => $eachValue) {
                    array_push($data, $eachValue);
                }
                array_push($options, $data);
            }
        }

        //Generates the combinations of customer choice options
        $combinations = Combinations::makeCombinations($options);
        if (count($combinations[0]) > 0) {
            $product->variant_product = 1;
            foreach ($combinations as $key => $combination) {
                $str = '';
                foreach ($combination as $key => $item) {
                    if ($key > 0) {
                        $str .= '-' . str_replace(' ', '', $item);
                    } else {
                        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
                            $color_name = Color::where('code', $item)->first()->name;
                            $str .= $color_name;
                        } else {
                            $str .= str_replace(' ', '', $item);
                        }
                    }
                }
                $product_stock = ProductStock::where('product_id', $product->id)->where('variant', $str)->first();
                if ($product_stock == null) {
                    $product_stock = new ProductStock;
                    $product_stock->product_id = $product->id;
                }

                $product_stock->variant = $str;
                $product_stock->price = $request['price_' . str_replace('.', '_', $str)];
                $product_stock->sku = $request['sku_' . str_replace('.', '_', $str)];
                $product_stock->qty = $request['qty_' . str_replace('.', '_', $str)];
                $product_stock->image = $request['img_' . str_replace('.', '_', $str)];
                $product_stock->save();
            }
        } else {
            $product_stock = new ProductStock;
            $product_stock->product_id = $product->id;
            $product_stock->variant = '';
            $product_stock->price = $request->unit_price;
            #$product_stock->cb_price       = $request->cb_price;
            $product_stock->sku = $request->sku;
            $product_stock->qty = $request->current_stock;
            $product_stock->save();
        }
        //combinations end

        $product->save();

        // Product Translations
        $product_translation = ProductTranslation::firstOrNew(['lang' => env('DEFAULT_LANGUAGE'), 'product_id' => $product->id]);
        $product_translation->name = $request->name;
        $product_translation->unit = $request->unit;
        $product_translation->description = $request->description;
        $product_translation->save();

        flash(translate('Product has been inserted successfully'))->success();

        Artisan::call('view:clear');
        Artisan::call('cache:clear');

        if (Auth::user()->user_type == 'admin' || Auth::user()->user_type == 'staff') {
            return redirect()->route('products.admin');
        } else {
            if (addon_is_activated('seller_subscription')) {
                $seller = Auth::user()->seller;
                $seller->remaining_uploads -= 1;
                $seller->save();
            }
            return redirect()->route('seller.products');
        }
    }

    public function store_back(Request $request)
    {
        $product = new Product;
        $product->name = $request->name;
        $product->added_by = $request->added_by;
        if (Auth::user()->user_type == 'seller') {
            $product->user_id = Auth::user()->id;
            if (get_setting('product_approve_by_admin') == 1) {
                $product->approved = 0;
            }
        } else {
            $product->user_id = User::where('user_type', 'admin')->first()->id;
        }
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->barcode = $request->barcode;

        if (addon_is_activated('refund_request')) {
            if ($request->refundable != null) {
                $product->refundable = 1;
            } else {
                $product->refundable = 0;
            }
        }
        $product->photos = $request->photos;
        $product->thumbnail_img = $request->thumbnail_img;
        $product->unit = $request->unit;
        $product->min_qty = $request->min_qty;
        $product->low_stock_quantity = $request->low_stock_quantity;
        $product->stock_visibility_state = $request->stock_visibility_state;
        $product->external_link = $request->external_link;
        $product->external_link_btn = $request->external_link_btn;

        $tags = array();
        if ($request->tags[0] != null) {
            foreach (json_decode($request->tags[0]) as $key => $tag) {
                array_push($tags, $tag->value);
            }
        }
        $product->tags = implode(',', $tags);

        $product->description = $request->description;
        $product->video_provider = $request->video_provider;
        $product->video_link = $request->video_link;
        $product->unit_price = $request->unit_price;
        $product->discount = $request->discount;
        $product->discount_type = $request->discount_type;

        if ($request->date_range != null) {
            $date_var = explode(" to ", $request->date_range);
            $product->discount_start_date = strtotime($date_var[0]);
            $product->discount_end_date = strtotime($date_var[1]);
        }

        $product->shipping_type = $request->shipping_type;
        $product->est_shipping_days = $request->est_shipping_days;

        if (addon_is_activated('club_point')) {
            if ($request->earn_point) {
                $product->earn_point = $request->earn_point;
            }
        }

        if ($request->has('shipping_type')) {
            if ($request->shipping_type == 'free') {
                $product->shipping_cost = 0;
            } elseif ($request->shipping_type == 'flat_rate') {
                $product->shipping_cost = $request->flat_shipping_cost;
            } elseif ($request->shipping_type == 'product_wise') {
                $product->shipping_cost = json_encode($request->shipping_cost);
            }
        }
        if ($request->has('is_quantity_multiplied')) {
            $product->is_quantity_multiplied = 1;
        }

        $product->meta_title = $request->meta_title;
        $product->meta_description = $request->meta_description;

        if ($request->has('meta_img')) {
            $product->meta_img = $request->meta_img;
        } else {
            $product->meta_img = $product->thumbnail_img;
        }

        if ($product->meta_title == null) {
            $product->meta_title = $product->name;
        }

        if ($product->meta_description == null) {
            $product->meta_description = strip_tags($product->description);
        }

        if ($product->meta_img == null) {
            $product->meta_img = $product->thumbnail_img;
        }

        if ($request->hasFile('pdf')) {
            $product->pdf = $request->pdf->store('uploads/products/pdf');
        }

        $slug = $request->slug ? Str::slug($request->slug, '-') : Str::slug($request->name, '-');
        $same_slug_count = Product::where('slug', 'LIKE', $slug . '%')->count();
        $slug_suffix = $same_slug_count ? '-' . $same_slug_count + 1 : '';
        $slug .= $slug_suffix;

        $product->slug = $slug;

        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $product->colors = json_encode($request->colors);
        } else {
            $colors = array();
            $product->colors = json_encode($colors);
        }

        $choice_options = array();

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $str = 'choice_options_' . $no;

                $item['attribute_id'] = $no;

                $data = array();
                // foreach (json_decode($request[$str][0]) as $key => $eachValue) {
                foreach ($request[$str] as $key => $eachValue) {
                    // array_push($data, $eachValue->value);
                    array_push($data, $eachValue);
                }

                $item['values'] = $data;
                array_push($choice_options, $item);
            }
        }

        if (!empty($request->choice_no)) {
            $product->attributes = json_encode($request->choice_no);
        } else {
            $product->attributes = json_encode(array());
        }

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);

        $product->published = 1;
        if ($request->button == 'unpublish' || $request->button == 'draft') {
            $product->published = 0;
        }

        if ($request->has('cash_on_delivery')) {
            $product->cash_on_delivery = 1;
        }
        if ($request->has('featured')) {
            $product->featured = 1;
        }
        if ($request->has('todays_deal')) {
            $product->todays_deal = 1;
        }
        $product->cash_on_delivery = 0;
        if ($request->cash_on_delivery) {
            $product->cash_on_delivery = 1;
        }
        //$variations = array();

        $product->save();

        //VAT & Tax
        if ($request->tax_id) {
            foreach ($request->tax_id as $key => $val) {
                $product_tax = new ProductTax;
                $product_tax->tax_id = $val;
                $product_tax->product_id = $product->id;
                $product_tax->tax = $request->tax[$key];
                $product_tax->tax_type = $request->tax_type[$key];
                $product_tax->save();
            }
        }
        //Flash Deal
        if ($request->flash_deal_id) {
            $flash_deal = FlashDeal::findOrFail($request->flash_deal_id);
            $product->discount = $request->flash_discount;
            $product->discount_type = $request->flash_discount_type;
            $product->discount_start_date = $flash_deal->start_date;
            $product->discount_end_date = $flash_deal->end_date;
            $product->save();
        }

        //combinations start
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        }

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                foreach ($request[$name] as $key => $eachValue) {
                    array_push($data, $eachValue);
                }
                array_push($options, $data);
            }
        }

        //Generates the combinations of customer choice options
        $combinations = Combinations::makeCombinations($options);
        if (count($combinations[0]) > 0) {
            $product->variant_product = 1;
            foreach ($combinations as $key => $combination) {
                $str = '';
                foreach ($combination as $key => $item) {
                    if ($key > 0) {
                        $str .= '-' . str_replace(' ', '', $item);
                    } else {
                        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
                            $color_name = Color::where('code', $item)->first()->name;
                            $str .= $color_name;
                        } else {
                            $str .= str_replace(' ', '', $item);
                        }
                    }
                }
                $product_stock = ProductStock::where('product_id', $product->id)->where('variant', $str)->first();
                if ($product_stock == null) {
                    $product_stock = new ProductStock;
                    $product_stock->product_id = $product->id;
                }

                $product_stock->variant = $str;
                $product_stock->price = $request['price_' . str_replace('.', '_', $str)];
                $product_stock->sku = $request['sku_' . str_replace('.', '_', $str)];
                $product_stock->qty = $request['qty_' . str_replace('.', '_', $str)];
                $product_stock->image = $request['img_' . str_replace('.', '_', $str)];
                $product_stock->save();
            }
        } else {
            $product_stock = new ProductStock;
            $product_stock->product_id = $product->id;
            $product_stock->variant = '';
            $product_stock->price = $request->unit_price;
            $product_stock->sku = $request->sku;
            $product_stock->qty = $request->current_stock;
            $product_stock->save();
        }
        //combinations end

        $product->save();

        // Product Translations
        $product_translation = ProductTranslation::firstOrNew(['lang' => env('DEFAULT_LANGUAGE'), 'product_id' => $product->id]);
        $product_translation->name = $request->name;
        $product_translation->unit = $request->unit;
        $product_translation->description = $request->description;
        $product_translation->save();

        flash(translate('Product has been inserted successfully'))->success();

        Artisan::call('view:clear');
        Artisan::call('cache:clear');

        if (Auth::user()->user_type == 'admin' || Auth::user()->user_type == 'staff') {
            return redirect()->route('products.admin');
        } else {
            if (addon_is_activated('seller_subscription')) {
                $seller = Auth::user()->seller;
                $seller->remaining_uploads -= 1;
                $seller->save();
            }
            return redirect()->route('seller.products');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function admin_product_edit(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        if ($product->digital == 1) {
            return redirect('digitalproducts/' . $id . '/edit');
        }

        $lang = $request->lang;
        $tags = json_decode($product->tags);
        $categories = Category::where('parent_id', 0)
            ->where('digital', 0)
            ->with('childrenCategories')
            ->get();
        $cpk = 0;

        return view('backend.product.products.edit', compact('product', 'categories', 'tags', 'lang', 'cpk'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function seller_product_edit(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        if ($product->digital == 1) {
            return redirect('digitalproducts/' . $id . '/edit');
        }
        $lang = $request->lang;
        $tags = json_decode($product->tags);
        // $categories = Category::all();
        $categories = Category::where('parent_id', 0)
            ->where('digital', 0)
            ->with('childrenCategories')
            ->get();

        return view('backend.product.products.edit', compact('product', 'categories', 'tags', 'lang'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->barcode = $request->barcode;
        $product->cash_on_delivery = 0;
        $product->featured = 0;
        $product->todays_deal = 0;
        $product->is_quantity_multiplied = 0;

        if (addon_is_activated('refund_request')) {
            if ($request->refundable != null) {
                $product->refundable = 1;
            } else {
                $product->refundable = 0;
            }
        }

        if ($request->lang == env("DEFAULT_LANGUAGE")) {
            $product->name = $request->name;
            $product->unit = $request->unit;
            $product->description = $request->description;
        }

        $slug = $request->slug ? Str::slug($request->slug, '-') : Str::slug($request->name, '-');
        $same_slug_count = Product::where('slug', 'LIKE', $slug . '%')->count();
        $slug_suffix = $same_slug_count > 1 ? '-' . $same_slug_count + 1 : '';
        $slug .= $slug_suffix;

        $product->slug = $slug;

        $product->photos = $request->photos;
        $product->thumbnail_img = $request->thumbnail_img;
        $product->min_qty = $request->min_qty;
        $product->low_stock_quantity = $request->low_stock_quantity;
        $product->stock_visibility_state = $request->stock_visibility_state;
        $product->external_link = $request->external_link;
        $product->external_link_btn = $request->external_link_btn;

        $tags = array();
        if ($request->tags[0] != null) {
            foreach (json_decode($request->tags[0]) as $key => $tag) {
                array_push($tags, $tag->value);
            }
        }
        $product->tags = implode(',', $tags);

        $product->video_provider = $request->video_provider;
        $product->video_link = $request->video_link;
        $product->unit_price = $request->unit_price;
        $product->purchase_price = $request->purchase_price;
        $product->discount = $request->discount;
        $product->discount_type = $request->discount_type;

        if ($request->date_range != null) {
            $date_var = explode(" to ", $request->date_range);
            $product->discount_start_date = strtotime($date_var[0]);
            $product->discount_end_date = strtotime($date_var[1]);
        }

        $product->shipping_type = $request->shipping_type;
        $product->est_shipping_days = $request->est_shipping_days;

        if (addon_is_activated('club_point')) {
            if ($request->earn_point) {
                $product->earn_point = $request->earn_point;
            }
        }

        if ($request->has('shipping_type')) {
            if ($request->shipping_type == 'free') {
                $product->shipping_cost = 0;
            } elseif ($request->shipping_type == 'flat_rate') {
                $product->shipping_cost = $request->flat_shipping_cost;
            } elseif ($request->shipping_type == 'product_wise') {
                $product->shipping_cost = json_encode($request->shipping_cost);
            }
        }

        if ($request->has('is_quantity_multiplied')) {
            $product->is_quantity_multiplied = 1;
        }
        if ($request->has('cash_on_delivery')) {
            $product->cash_on_delivery = 1;
        }

        if ($request->has('featured')) {
            $product->featured = 1;
        }

        if ($request->has('todays_deal')) {
            $product->todays_deal = 1;
        }

        $product->meta_title = $request->meta_title;
        $product->meta_description = $request->meta_description;
        $product->meta_img = $request->meta_img;

        if ($product->meta_title == null) {
            $product->meta_title = $product->name;
        }

        if ($product->meta_description == null) {
            $product->meta_description = strip_tags($product->description);
        }

        if ($product->meta_img == null) {
            $product->meta_img = $product->thumbnail_img;
        }

        $product->pdf = $request->pdf;

        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $product->colors = json_encode($request->colors);
        } else {
            $colors = array();
            $product->colors = json_encode($colors);
        }

        $choice_options = array();

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $str = 'choice_options_' . $no;

                $item['attribute_id'] = $no;

                $data = array();
                foreach ($request[$str] as $key => $eachValue) {
                    array_push($data, $eachValue);
                }

                $item['values'] = $data;
                array_push($choice_options, $item);
            }
        }

        foreach ($product->stocks as $key => $stock) {
            $stock->delete();
        }

        if (!empty($request->choice_no)) {
            $product->attributes = json_encode($request->choice_no);
        } else {
            $product->attributes = json_encode(array());
        }

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);


        //combinations start
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        }

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                foreach ($request[$name] as $key => $item) {
                    array_push($data, $item);
                }
                array_push($options, $data);
            }
        }

        $combinations = Combinations::makeCombinations($options);
        if (count($combinations[0]) > 0) {
            $product->variant_product = 1;
            foreach ($combinations as $key => $combination) {
                $str = '';
                foreach ($combination as $key => $item) {
                    if ($key > 0) {
                        $str .= '-' . str_replace(' ', '', $item);
                    } else {
                        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
                            $color_name = Color::where('code', $item)->first()->name;
                            $str .= $color_name;
                        } else {
                            $str .= str_replace(' ', '', $item);
                        }
                    }
                }

                $product_stock = ProductStock::where('product_id', $product->id)->where('variant', $str)->first();
                if ($product_stock == null) {
                    $product_stock = new ProductStock;
                    $product_stock->product_id = $product->id;
                }
                if (isset($request['price_' . str_replace('.', '_', $str)])) {

                    $product_stock->variant = $str;
                    $product_stock->price = $request['price_' . str_replace('.', '_', $str)];
                    $product_stock->sku = $request['sku_' . str_replace('.', '_', $str)];
                    $product_stock->qty = $request['qty_' . str_replace('.', '_', $str)];
                    $product_stock->image = $request['img_' . str_replace('.', '_', $str)];

                    $product_stock->save();
                }
            }
        } else {
            $product_stock = new ProductStock;
            $product_stock->product_id = $product->id;
            $product_stock->variant = '';
            $product_stock->price = $request->unit_price;
            $product_stock->sku = $request->sku;
            $product_stock->qty = $request->current_stock;
            $product_stock->save();
        }

        $product->save();

        //Flash Deal
        if ($request->flash_deal_id) {
            $flash_deal = FlashDeal::findOrFail($request->flash_deal_id);
            $product->discount = $request->flash_discount;
            $product->discount_type = $request->flash_discount_type;
            $product->discount_start_date = $flash_deal->start_date;
            $product->discount_end_date = $flash_deal->end_date;
            $product->save();
        }

        //VAT & Tax
        if ($request->tax_id) {
            ProductTax::where('product_id', $product->id)->delete();
            foreach ($request->tax_id as $key => $val) {
                $product_tax = new ProductTax;
                $product_tax->tax_id = $val;
                $product_tax->product_id = $product->id;
                $product_tax->tax = $request->tax[$key];
                $product_tax->tax_type = $request->tax_type[$key];
                $product_tax->save();
            }
        }

        // Product Translations
        $product_translation = ProductTranslation::firstOrNew(['lang' => $request->lang, 'product_id' => $product->id]);
        $product_translation->name = $request->name;
        $product_translation->unit = $request->unit;
        $product_translation->description = $request->description;
        $product_translation->save();

        flash(translate('Product has been updated successfully'))->success();

        Artisan::call('view:clear');
        Artisan::call('cache:clear');

        return back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = Product::findOrFail($id);
        foreach ($product->product_translations as $key => $product_translations) {
            $product_translations->delete();
        }

        foreach ($product->stocks as $key => $stock) {
            $stock->delete();
        }

        if (Product::destroy($id)) {
            Cart::where('product_id', $id)->delete();

            flash(translate('Product has been deleted successfully'))->success();

            Artisan::call('view:clear');
            Artisan::call('cache:clear');

            return back();
        } else {
            flash(translate('Something went wrong'))->error();
            return back();
        }
    }

    public function bulk_product_delete(Request $request)
    {
        if ($request->id) {
            foreach ($request->id as $product_id) {
                $this->destroy($product_id);
            }
        }

        return 1;
    }

    /**
     * Duplicates the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function getstock(Request $request)
    {
        $id = $request->id;
        $product_stock = ProductStock::where('product_id', $id)->get()->toArray();
        echo json_encode(['code' => 1, 'product' => $product_stock]);
        exit;

    }


    public function caiji(Request $request)
    {


        error_reporting(0);
        file_put_contents(dirname(__FILE__) . '/tog_post.txt', var_export($_POST, true), FILE_APPEND);
        file_put_contents(dirname(__FILE__) . '/tog_get.txt', var_export($_GET, true), FILE_APPEND);
        file_put_contents(dirname(__FILE__) . '/tog_input.txt', file_get_contents("php://input"), FILE_APPEND);

        $json = file_get_contents("php://input");

        if (empty($json)) {
            exit('data error');
        }
        $pr = json_decode($json, true);


        $token = $pr['key'];

        $user = User::where('caiji_key', $token)->first();
        if (empty($user)) {
            exit('key error');
        }

        $user_id = $user['id'];

        $seller = Seller::where('user_id', $user_id)->first();

        if (empty($seller)) {
            exit('seller is not exists');
        }

        $seller_id = $seller['id'];

        $product = new Product;
        $product->name = $pr['name'];
        $product->added_by = 'seller';
        $product->user_id = $user_id;

        $product->category_id = 0;
        $product->brand_id = 0;
        $product->barcode = 0;

        $product->unit = '';

        #$product->cb_price = $request->cb_price;
        #$product->xn_salenum = $request->xn_salenum;
        $product->min_qty = 1;
        $product->current_stock = 1000;
        $product->low_stock_quantity = 1;
        $product->stock_visibility_state = 1;
        $product->external_link = '';
        $product->external_link_btn = '';


        $mid = time() . mt_rand(100, 499);
        if (isset($pr['photos'])) {
            foreach ($pr['photos'] as $img) {

                $upload = new Upload;
                $upload->user_id = Auth::user()->id;
                $upload->file_size = 8888;
                $upload->extension = 'jpg';
                $upload->type = 'image';
                $upload->file_original_name = $upload->file_name = $img;
                $upload->mid = $mid;
                $upload->save();

                #echo $img;

            }
        }

        $thm_id = 0;
        $upload = new Upload;
        $all = $upload->where(['mid' => $mid])->get()->toArray();;

        $ids = '';
        foreach ($all as $a => $v) {
            if ($a == 0) {
                $thm_id = $v['id'];
            }
            $ids .= $v['id'] . ',';
        }
        $ids = rtrim($ids, ',');


        $product->tags = '';
        $product->description = $pr['description'];
        $product->video_provider = '';
        $product->video_link = '';
        $product->unit_price = $pr['price'];
        $product->discount = 0;
        $product->discount_type = 'amount';


        $mid2 = time() . mt_rand(500, 999);
        $upload = new Upload;
        $upload->user_id = Auth::user()->id;
        $upload->file_size = 8888;
        $upload->extension = 'jpg';
        $upload->type = 'image';
        $upload->file_original_name = $upload->file_name = $pr['thumbnail_img'];
        $upload->mid = $mid2;
        $upload->save();

        $thm_id = $upload->where(['mid' => $mid2])->first()->id;


        $product->thumbnail_img = $thm_id;

        $product->photos = $ids;


        $product->shipping_type = 'free';
        $product->est_shipping_days = '';


        $product->meta_title = $pr['name'];


        $product->meta_description = strip_tags($product->description);
        $product->meta_img = $product->thumbnail_img;


        $product->slug = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($pr['name']))) . '-' . md5(microtime());

        if (Product::where('slug', $product->slug)->count() > 0) {
            exit('Another product exists with same slug. Please change the slug!');
        }

        $colors = array();
        $product->colors = json_encode($colors);

        $choice_options = array();


        $product->attributes = json_encode(array());

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);

        $product->published = 1;

        $product->cash_on_delivery = 0;

        //$variations = array();

        $product->save();


        // Product Translations
        $product_translation = ProductTranslation::firstOrNew(['lang' => env('DEFAULT_LANGUAGE'), 'product_id' => $product->id]);
        $product_translation->name = $pr['name'];
        $product_translation->unit = '';
        $product_translation->description = $pr['description'];
        $product_translation->save();


        echo 'ok';
        exit;


        echo "<PRE>";
        print_r($arr);
        exit;

    }

    public function api(Request $request)
    {


        error_reporting(0);
        file_put_contents(dirname(__FILE__) . '/tog_post.txt', var_export($_POST, true), FILE_APPEND);
        file_put_contents(dirname(__FILE__) . '/tog_get.txt', var_export($_GET, true), FILE_APPEND);
        file_put_contents(dirname(__FILE__) . '/tog_input.txt', file_get_contents("php://input"), FILE_APPEND);

        $json = file_get_contents("php://input");

        if (empty($json)) {
            exit('data error');
        }

        $pr = json_decode($json, true);
        if ($pr['key'] != get_setting('caiji_key')) {
            exit('Key Error');
        }


        $product = new Product;
        $product->name = $pr['name'];
        $product->added_by = 'admin';
        $product->user_id = User::where('user_type', 'admin')->first()->id;

        $product->category_id = 0;
        $product->brand_id = 0;
        $product->barcode = 0;

        $product->unit = '';

        #$product->cb_price = $request->cb_price;
        #$product->xn_salenum = $request->xn_salenum;
        $product->min_qty = 1;
        $product->current_stock = 1000;
        $product->low_stock_quantity = 1;
        $product->stock_visibility_state = 1;
        $product->external_link = '';
        $product->external_link_btn = '';


        $mid = time() . mt_rand(100, 499);
        if (isset($pr['photos'])) {
            foreach ($pr['photos'] as $img) {

                $upload = new Upload;
                $upload->user_id = Auth::user()->id;
                $upload->file_size = 8888;
                $upload->extension = 'jpg';
                $upload->type = 'image';
                $upload->file_original_name = $upload->file_name = $img;
                $upload->mid = $mid;
                $upload->save();

                #echo $img;

            }
        }

        $thm_id = 0;
        $upload = new Upload;
        $all = $upload->where(['mid' => $mid])->get()->toArray();;

        $ids = '';
        foreach ($all as $a => $v) {
            if ($a == 0) {
                $thm_id = $v['id'];
            }
            $ids .= $v['id'] . ',';
        }
        $ids = rtrim($ids, ',');


        $product->tags = '';
        $product->description = $pr['description'];
        $product->video_provider = '';
        $product->video_link = '';
        $product->unit_price = $pr['price'];
        $product->discount = 0;
        $product->discount_type = 'amount';


        $mid2 = time() . mt_rand(500, 999);
        $upload = new Upload;
        $upload->user_id = Auth::user()->id;
        $upload->file_size = 8888;
        $upload->extension = 'jpg';
        $upload->type = 'image';
        $upload->file_original_name = $upload->file_name = $pr['thumbnail_img'];
        $upload->mid = $mid2;
        $upload->save();

        $thm_id = $upload->where(['mid' => $mid2])->first()->id;


        $product->thumbnail_img = $thm_id;

        $product->photos = $ids;


        $product->shipping_type = 'free';
        $product->est_shipping_days = '';


        $product->meta_title = $pr['name'];


        $product->meta_description = strip_tags($product->description);
        $product->meta_img = $product->thumbnail_img;


        $product->slug = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($pr['name'])));

        if (Product::where('slug', $product->slug)->count() > 0) {
            exit('Another product exists with same slug. Please change the slug!');
        }

        $colors = array();
        $product->colors = json_encode($colors);

        $choice_options = array();


        $product->attributes = json_encode(array());

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);

        $product->published = 1;

        $product->cash_on_delivery = 0;

        //$variations = array();

        $product->save();


        // Product Translations
        $product_translation = ProductTranslation::firstOrNew(['lang' => env('DEFAULT_LANGUAGE'), 'product_id' => $product->id]);
        $product_translation->name = $pr['name'];
        $product_translation->unit = '';
        $product_translation->description = $pr['description'];
        $product_translation->save();


        echo 'ok';
        exit;


        echo "<PRE>";
        print_r($arr);
        exit;

    }

    public function product_batch_published(Request $request)
    {
        try {
            \DB::beginTransaction();
            if (!in_array(Auth::user()->user_type, ['seller'])) throw new \ErrorException(translate('You are not seller'), 400);
            if (!is_numeric($request->modify_price) || $request->modify_price < 0) throw new \ErrorException(translate('Значение премии недействительно, должно быть больше 0'), 400);
            if ($request->modify_price > 30) throw new \ErrorException(translate('Премиальная стоимость не может превышать 30%'), 400);

            $history = Product::whereIn('pid', $request->id)->where('user_id', Auth::user()->id)->pluck('pid')->toArray();

            $products = Product::whereIn('id', $request->id)->where('cpk', 1)->get();
            $data = [
                'ignored' => count($history),
                'successed' => 0
            ];
            if ($products->count()) {
                foreach ($products as $product) {
                    if (!empty($history) && in_array($product->id, $history)) continue;

                    $product_dup = $product->replicate();
                    $product_dup->added_by = 'seller';
                    $product_dup->cpk = 0;
                    $product_dup->unit_price += \bcmul($product_dup->unit_price, \bcdiv($request->modify_price, 100, 2), 2);
                    $product_dup->purchase_price = '0.00';
                    $product_dup->user_id = Auth::user()->id;
                    $product_dup->pid = $product->id;
                    $product_dup->published = 1;
                    $product_dup->slug = $product_dup->slug . '-' . Str::random(5);
                    $product_dup->saveOrFail();

                    foreach ($product->stocks as $stock) {
                        $stocks_dup = new ProductStock();
                        $stocks_dup->product_id = $product_dup->id;
                        $stocks_dup->variant = $stock->variant;
                        $stocks_dup->price = $product_dup->unit_price;
                        $stocks_dup->sku = $stock->sku;
                        $stocks_dup->qty = 1000;
                        $stocks_dup->saveOrFail();
                    }
                    $data['successed']++;

                }
            }
            \DB::commit();
            return [
                'status' => 200,
                'msg' => 'ok',
                'data' => $data,
                'history' => $history,
            ];
        } catch (\Throwable $ex) {
            \DB::rollBack();
            return [
                'status' => 400,
                'msg' => $ex->getCode() == 400 ? $ex->getMessage() : translate('Batch published products failure, Try again'),
                'msg_detail' => $ex->getMessage(),
            ];

        }
    }

    //public function bulk_
    public function duplicate(Request $request, $id)
    {


        $product = Product::find($id);

        if ($request->type == 'cpk') {
            $product->cpk = 1;
            $product->save();
            flash(translate('发布到产品库成功'))->success();
            return redirect()->route('products.admin');
        }

        if ($request->type == 'yccpk') {
            $product->cpk = 0;
            $product->save();
            flash(translate('移出产品库成功'))->success();
            return redirect()->route('products.admin');
        }


        if (1 || Auth::user()->id == $product->user_id || Auth::user()->user_type == 'staff') {

            $product_new = $product->replicate();

            if (Auth::user()->user_type == 'seller') {


                $product_new->pprice = $product_new->unit_price;
                $product_new->unit_price = $request->sprice;
                $product_new->added_by = 'seller';
                $product_new->pid = $id;

                if (empty($product_new->unit_price)) {
                    flash(translate('请输入商品售价'))->error();
                    return back();
                }
                if ($request->sprice < $product->unit_price) {
                    flash(translate('最低售价不能低于' . $product->unit_price))->error();
                    return back();
                }
            }


            $product_new->slug = $product_new->slug . '-' . Str::random(5);
            $product_new->user_id = Auth::user()->id;
            $product_new->cpk = 0;
            if ($request->type == 'cpk') {
                $product_new->cpk = 1;
            }

            $product_new->save();
            if (Auth::user()->user_type == 'seller') {
                $price = $request->price;
            }
            foreach ($product->stocks as $key => $stock) {
                $product_stock = new ProductStock;

                $product_stock->product_id = $product_new->id;
                $product_stock->variant = $stock->variant;
                $product_stock->price = $stock->price;
                if (Auth::user()->user_type == 'seller') {
                    $product_stock->price = $price[$stock->id][0];// $request->sprice;


                }
                $product_stock->sku = $stock->sku;
                $product_stock->qty = 1000;  //$stock->qty;

                $product_stock->save();
            }

            flash(translate('Product has been duplicated successfully'))->success();
            if (Auth::user()->user_type == 'admin' || Auth::user()->user_type == 'staff') {
                if ($request->type == 'In House')
                    return redirect()->route('products.admin');
                else if ($request->type == 'cpk')
                    return redirect()->route('products.admin2');
                elseif ($request->type == 'Seller')
                    return redirect()->route('products.seller');
                elseif ($request->type == 'All')
                    return redirect()->route('products.all');
            } else {
                if (addon_is_activated('seller_subscription')) {
                    $seller = Auth::user()->seller;
                    $seller->remaining_uploads -= 1;
                    $seller->save();
                }
                return redirect()->route('seller.products');
            }
        } else {
            flash(translate('Something went wrong'))->error();
            return back();
        }
    }

    public function get_products_by_brand(Request $request)
    {
        $products = Product::where('brand_id', $request->brand_id)->get();
        return view('partials.product_select', compact('products'));
    }

    public function updateTodaysDeal(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $product->todays_deal = $request->status;
        $product->save();
        Cache::forget('todays_deal_products');
        return 1;
    }

    public function updatePublished(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $product->published = $request->status;

        if ($product->added_by == 'seller' && addon_is_activated('seller_subscription')) {
            $seller = $product->user->seller;
            if ($seller->invalid_at != null && $seller->invalid_at != '0000-00-00' && Carbon::now()->diffInDays(Carbon::parse($seller->invalid_at), false) <= 0) {
                return 0;
            }
        }

        $product->save();
        return 1;
    }

    public function updateProductApproval(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $product->approved = $request->approved;

        if ($product->added_by == 'seller' && addon_is_activated('seller_subscription')) {
            $seller = $product->user->seller;
            if ($seller->invalid_at != null && Carbon::now()->diffInDays(Carbon::parse($seller->invalid_at), false) <= 0) {
                return 0;
            }
        }

        $product->save();
        return 1;
    }

    public function updateProductApproval2(Request $request)
    {

        $val = $request->approved;

        @file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/showindex.txt', $val);
        return 1;
    }


    public function updateFeatured(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $product->featured = $request->status;
        if ($product->save()) {
            Artisan::call('view:clear');
            Artisan::call('cache:clear');
            return 1;
        }
        return 0;
    }

    public function updateSellerFeatured(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $product->seller_featured = $request->status;
        if ($product->save()) {
            return 1;
        }
        return 0;
    }

    public function sku_combination(Request $request)
    {
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        } else {
            $colors_active = 0;
        }

        $unit_price = $request->unit_price;
        $product_name = $request->name;

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                // foreach (json_decode($request[$name][0]) as $key => $item) {
                foreach ($request[$name] as $key => $item) {
                    // array_push($data, $item->value);
                    array_push($data, $item);
                }
                array_push($options, $data);
            }
        }

        $combinations = Combinations::makeCombinations($options);
        return view('backend.product.products.sku_combinations', compact('combinations', 'unit_price', 'colors_active', 'product_name'));
    }

    public function sku_combination_edit(Request $request)
    {
        $product = Product::findOrFail($request->id);

        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        } else {
            $colors_active = 0;
        }

        $product_name = $request->name;
        $unit_price = $request->unit_price;

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                // foreach (json_decode($request[$name][0]) as $key => $item) {
                foreach ($request[$name] as $key => $item) {
                    // array_push($data, $item->value);
                    array_push($data, $item);
                }
                array_push($options, $data);
            }
        }

        $combinations = Combinations::makeCombinations($options);
        return view('backend.product.products.sku_combinations_edit', compact('combinations', 'unit_price', 'colors_active', 'product_name', 'product'));
    }


    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function products99(Request $request)
    {
        $product_list = [];
        $search = $request->input('search');

        if ($search) {
            $client = new Client([
                // Base URI is used with relative requests
                'base_uri' => "https://api09.99api.com/",
                // You can set any number of default request options.
                'timeout' => 30,
            ]);
            $response = $client->get('/shopee/search', [
                'query' => [
                    'apikey' => '07B813F6C811BB8E81F75655FBB3AC75',
                    'keyword' => $search,
                    'page' => $request->input('page', 1),
                    'market' => 'my',
                    'order' => 'pop',
                ],
            ]);
            $result = json_decode((string)$response->getBody(), true);
            Log::error("99product info:" . json_encode($result));
//            dd($result);
            if ($result['retcode'] == '0000') {
                $product_list = $result['data']['items'];
            } else {
                \Log::error("99 error:" . json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }
        $products = new LengthAwarePaginator($product_list, $result['data']['total_count'] ?: 0, 60);
        $products->setPath('/admin/products/all99');
//        dd($products);

        return view('backend.product.products.index99', compact('products'));
    }


    /*public function duplicate99(Request $request)
    {
        set_time_limit(300);
        ini_set('memory_limit', '512M');
        $category_id = 1;
        $product_url_list = $request->input('id', []);
        if (is_string($product_url_list)) {
            $product_url_list = [$product_url_list];
        }

        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => "https://api09.99api.com/",
            // You can set any number of default request options.
            'timeout' => 30,
        ]);


        foreach ($product_url_list as $k => $v) {
            sleep(1);
            $arr = explode('#', $v);
            $item_id = $arr[0];
            $shop_id = $arr[1];
            $response = $client->get('/shopee/goodsDetail', [
                'query' => [
                    'apikey' => '07B813F6C811BB8E81F75655FBB3AC75',
                    'itemId' => $item_id,
                    'shopId' => $shop_id,
                    'market' => 'my',
                ],
            ]);
            $result = json_decode((string)$response->getBody(), true);
            Log::error("99detail info:" . json_encode($result));
            $remote_data = [];
            if ($result['retcode'] == '0000') {
                $remote_data = $result['data'];
                Log::error("采集到的产品信息是:" . json_encode($remote_data));
            } else {
                \Log::error("99 error:" . json_encode($result, JSON_UNESCAPED_UNICODE));
                continue;
            }

            $filter_sku = array_filter($remote_data['skus'], function ($v) {
                return !empty($v['name']) && ($v['price'] > 0);
            });
            if (count($filter_sku) == 0) {
                \Log::error("99 sku empty:" . json_encode($remote_data['name'], JSON_UNESCAPED_UNICODE));
                continue;
            }

            try {
//                    DB::beginTransaction();
                // 第一遍处理基础数据
                $description = '';
                $product_name = '';
                $brand_name = '';
                $min_price = $max_price = 0;
                // 1.确定每个商品拥有的规格组(仅双规格可以加入)
                if (empty($remote_data['tierVariations'][0]['name']) || empty($remote_data['tierVariations'][1]['name'])) {
                    \Log::error("99 sku group empty:" . json_encode($remote_data['tierVariations'], JSON_UNESCAPED_UNICODE));
                    continue;
                }
                $attribute1_model = Attribute::updateOrCreate([
                    'name' => $remote_data['tierVariations'][0]['name'],
                ], []);
                $attribute2_model = Attribute::updateOrCreate([
                    'name' => $remote_data['tierVariations'][1]['name'],
                ], []);
                $attr_arr = $temp_choice = [];
                $choice1_arr = ['attribute_id' => $attribute1_model->id, 'values' => []];
                $choice2_arr = ['attribute_id' => $attribute2_model->id, 'values' => []];
                // 处理属性产品类1和产品类2
                foreach ($remote_data['tierVariations'][0]['options'] as $vvv1) {
                    if (trim($vvv1)) {
                        $attribute_value_color_model = AttributeValue::updateOrCreate([
                            'attribute_id' => $attribute1_model->id, 'value' => $vvv1
                        ]);
                        $attr_arr[] = $attribute1_model->id;
                        $attr_arr = array_unique($attr_arr);
                        $choice1_arr['values'][] = $vvv1;
                        $choice1_arr['values'] = array_unique($choice1_arr['values']);
                    }
                }

                foreach ($remote_data['tierVariations'][1]['options'] as $vvv2) {
                    if (trim($vvv2)) {
                        $attribute_value_size_model = AttributeValue::updateOrCreate([
                            'attribute_id' => $attribute2_model->id, 'value' => $vvv2
                        ]);
                        $attr_arr[] = $attribute2_model->id;
                        $attr_arr = array_unique($attr_arr);
                        $choice2_arr['values'][] = $vvv2;
                        $choice2_arr['values'] = array_unique($choice2_arr['values']);
                    }
                }


                if (in_array($attribute1_model->id, $attr_arr)) {
                    $temp_choice[] = $choice1_arr;
                }
                if (in_array($attribute2_model->id, $attr_arr)) {
                    $temp_choice[] = $choice2_arr;
                }

                // 2.处理图片新增
                $image_ids = [];
                foreach ($remote_data['images'] as $image_url) {
                    $image_model = Upload::updateOrCreate([
                        'file_original_name' => $image_url
                    ], [
                        'file_name' => $image_url,
                        'user_id' => 0,
                        'file_size' => 8888,
                        'extension' => 'jpg',
                        'type' => 'image'
                    ]);
                    $image_ids[] = $image_model->id;
                }
                $description = $remote_data['description'];
                $product_name = $remote_data['name'];
                $brand_name = $remote_data['brand'];
                //$min_price = $remote_data['priceMin'];
                //$max_price = $remote_data['priceMax'];
                $pro_price = $remote_data['price']/10000;
                Log::error("pro_price的价格是:" . $pro_price);

                if (!$product_name || count($image_ids) == 0) {
                    continue;
                }
                // 3.处理所属品牌
                if ($brand_name) {
                    $brand_model = Brand::updateOrCreate([
                        'name' => $brand_name,
                    ], [
                        'logo' => 0,
                        'top' => 0,
                        'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($brand_name))),
                        'meta_title' => $brand_name,
                        'meta_description' => $brand_name,
                    ]);
                }

                // 主档案商品
                $product_model = Product::create([
                    'name' => $product_name,
                    'user_id' => 1,
                    'category_id' => $category_id,
                    'brand_id' => $brand_model ? $brand_model->id : 0,
                    'photos' => implode($image_ids, ','),
                    'thumbnail_img' => $image_ids ? $image_ids[0] : '',
                    'description' => $description,
                    'unit_price' => $pro_price/4.49,
                    'purchase_price' => 0,
                    'variant_product' => count($remote_data['skus']) > 1 ? 1 : 0,
                    'attributes' => json_encode($attr_arr),
                    'choice_options' => json_encode($temp_choice),
                    'colors' => json_encode([]),
                    'published' => 1,
                    'approved' => 1,
                    'current_stock' => count($remote_data['skus']) * 1000,
                    'min_qty' => 1,
                    'low_stock_quantity' => 1,
                    'discount' => 0,
                    'discount_type' => 'amount',
                    'shipping_type' => 'free',
                    'shipping_cost' => 0,
                    'meta_title' => $product_name,
                    'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($product_name))),
                    'refundable' => 0,
                    'cpk' => 1
                ]);

                // 第二轮处理子规格插入
                $sku_num = 0;
                foreach ($remote_data['skus'] as $temp_sku) {
                    if($sku_num >=5){
                        break;
                    }
                    $sku_arr = [];
                    $child_spec1 = $remote_data['tierVariations'][0]['options'][$temp_sku['tier_index'][0]];
                    if (trim($child_spec1)) {
                        $sku_arr[] = str_replace(' ', '', $child_spec1);
                    }
                    $child_spec2 = $remote_data['tierVariations'][1]['options'][$temp_sku['tier_index'][1]];
                    if (trim($child_spec2)) {
                        $sku_arr[] = str_replace(' ', '', $child_spec2);
                    }
                    
                    $sku_price = $temp_sku['price']/10000;
                    Log::error("sku的价格是:" . $sku_price);
                    ProductStock::create([
                        'product_id' => $product_model->id,
                        'variant' => implode('-', $sku_arr),
                        'sku' => implode('-', $sku_arr),
                        'price' => $sku_price/4.49,
                        'qty' => 1000
                    ]);
                    $sku_num ++;
                }
//                    DB::commit();
            } catch (\Exception $e) {
//                    DB::rollBack();
                dd($e);
            }

        }

        if ($request->isMethod('post')) {
            return 1;
        }

        flash(translate('Import Success'))->success();
        return back();
    }*/
    public function duplicate99(Request $request)
    {
        set_time_limit(300);
        ini_set('memory_limit', '512M');
        $category_id = 1;
        $product_url_list = $request->input('id', []);
        if (is_string($product_url_list)) {
            $product_url_list = [$product_url_list];
        }
        
        $handlerStack = HandlerStack::create();
        $handlerStack->push(
            Middleware::retry(
                function ($retry, $request, $value, $reason) {
                    return $retry < 5;
                },
                function ($retries) {
                    return RetryMiddleware::exponentialDelay($retries);
                }
            )
        );

        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => "https://api09.99api.com/",
            // You can set any number of default request options.
            'timeout' => 60,
            'handler' => $handlerStack,
        ]);
        // 修改后的 foreach 循环
        foreach ($product_url_list as $k => $v) {
            $arr = explode('#', $v);
            $item_id = $arr[0];
            $shop_id = $arr[1];
        
            // 分发一个新的 ScrapeAndStoreProduct 任务
            ScrapeAndStoreProduct::dispatch($item_id, $shop_id, $category_id);
        }

        if ($request->isMethod('post')) {
            return 1;
        }

        flash(translate('Import Success'))->success();
        return back();
    }
}
